package com.web.wechat.web.admin;

import com.blue.core.dict.HttpMethod;
import com.blue.http.annotation.Http;
import com.blue.http.config.ErrorConfig;
import com.blue.http.message.HttpRequest;
import com.blue.http.message.UploadFile;
import com.blue.integration.serve.Bucket;
import com.blue.integration.serve.StorageClient;
import com.web.base.log.facade.UploadFacade;
import com.web.base.log.message.UploadRequest;
import com.web.base.log.message.UploadResponse;
import com.web.base.user.facade.UserFacade;
import com.web.base.user.message.UserRequest;
import com.web.wechat.global.model.User;
import com.web.wechat.global.util.HttpContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

/**
 * 文件上传
 *
 * @author zhengjin
 * @since 1.0 2018年06月28日
 */
@Controller("adminUploadController")
@Http(url = "/admin")
public class UploadController
{
	private static Logger logger = LoggerFactory.getLogger(UploadController.class);

	@Autowired
	private UserFacade userFacade;
	@Autowired
	private UploadFacade uploadFacade;
	@Autowired
	private StorageClient storageClient;
	@Autowired
	private HttpContext httpContext;

	private ErrorConfig errorConfig = ErrorConfig.getInstance();

	public UploadController()
	{
	}

	@Http(url = "/upload_file", method = HttpMethod.POST)
	public Object uploadFile(HttpRequest request)
	{
		User user = httpContext.getUser(request);
		UploadFile file = request.getFile();
		int type = request.getPostInt("type", 0);
		if (file == null)
			throw errorConfig.getException(ErrorConfig.ERROR_UPLOAD);

		try
		{
			String key = storageClient.save(Bucket.CMS, file.getInputStream(), file.getOriginalName(), null);
			UploadResponse response = this.addUpload(user, file, key);
			this.handleUpload(request, response, user, type);
			return response;
		}
		catch (Exception e)
		{
			logger.error(errorConfig.get(ErrorConfig.ERROR_UPLOAD) + "：", e);
			throw errorConfig.getException(ErrorConfig.ERROR_UPLOAD);
		}
	}

	private UploadResponse addUpload(User user, UploadFile file, String key)
	{
		UploadRequest request = new UploadRequest();
		request.setUserId(user.getId());
		request.setName(file.getOriginalName());
		request.setKey(key);
		request.setSize(file.getSize());
		request.setMimeType(file.getContentType());
		UploadResponse response = uploadFacade.add(request);
		return response;
	}
	private void handleUpload(HttpRequest request, UploadResponse response, User user, int type)
	{
		if (type == 1) // 用户头像
		{
			UserRequest userRequest = new UserRequest();
			userRequest.setId(user.getId());
			userRequest.setName(user.getName());
			userRequest.setPic(response.getKey());
			userFacade.update(userRequest);
			user.setPic(response.getKey());
			user.setPicUrl(response.getUrl());
			httpContext.setUser(request, user);
		}
	}

}
